﻿using System;
using System.Collections.ObjectModel;
using System.Data.Entity;
using System.Linq;
using System.Web.Mvc;
using EntityFramework.Extensions;
using Pyramid.Models;

namespace Pyramid.Controllers
{
	public class AttendanceController : BaseController
	{
		/// <summary>
		/// 考勤管理页面
		/// </summary>
		public ActionResult Manage(int? year, int? month)
		{
			var date = DateTime.Now.AddMonths(-1);
			var y = year ?? date.Year;
			var m = month ?? date.Month;
			if (y >= date.Year && m > date.Month)
			{
				ViewBag.Master = new AttendanceMaster
				                 {
					                 Year = y,
					                 Month = m
				                 };
				ViewBag.HasError = true;
				ViewBag.Message = string.Format("选择的月份不能晚于{0:yyyy年M月}，请重新选择！", date);
				return View();
			}

			var model = Db.AttendanceMasters
			              .Include(x => x.AttendanceDetails.Select(s => s.Staff.Position))
			              .Include(x => x.AttendanceDetails.Select(s => s.Staff.Department))
			              .FirstOrDefault(x => x.Year == y && x.Month == m) ?? new AttendanceMaster
			                                                                   {
				                                                                   Year = y,
				                                                                   Month = m,
				                                                                   AttendanceDetails = Db.Staves.Include(x => x.Position)
				                                                                                         .Include(x => x.Department)
				                                                                                         .ToList()
				                                                                                         .Select(x => new AttendanceDetail
				                                                                                                      {
					                                                                                                      ActualDays = 0,
					                                                                                                      StaffId = x.Id,
					                                                                                                      Staff = x
				                                                                                                      }).ToList(),
				                                                                   CreateTime = DateTime.Now,
				                                                                   ExpectedDays = 22,
				                                                                   CreateUserId = User.UserId,
				                                                                   Status = (int) DataStatus.New
			                                                                   };
			ViewBag.HasError = false;
			ViewBag.Master = model;
			return View();
		}

		[HttpPost]
		public ActionResult Edit(int id, FormCollection collection)
		{
			var master = new AttendanceMaster
			             {
				             CreateUserId = User.UserId,
				             EditUserId = User.UserId,
				             CreateTime = DateTime.Now,
				             EditTime = DateTime.Now
			             };
			if (id > 0)
			{
				master = Db.AttendanceMasters.Single(x => x.Id == id);
			}

			if (!TryUpdateModel(master)) return JError();
			var details = collection.AllKeys
			                        .Where(x => x.StartsWith("actualDays_"))
			                        .Select(key => new AttendanceDetail
			                                       {
				                                       StaffId = Convert.ToInt32(key.Substring("actualDays_".Length)),
				                                       ActualDays = Convert.ToInt32(collection[key])
			                                       }).ToList();

			master.AttendanceDetails = new Collection<AttendanceDetail>(details);

			if (master.Id > 0)
			{
				//delete details
				Db.AttendanceDetails.Delete(x => x.MasterId == master.Id);

				master.EditUserId = User.UserId;
				master.EditTime = DateTime.Now;
			}
			else
			{
				Db.AttendanceMasters.Add(master);
			}

			Db.SaveChanges();

			return JSuccess();
		}
	}
}